package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.ctc.wstx.util.StringUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


@Component
public class AccessFilter extends ZuulFilter {
    @Override
    //前置过滤器
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    //设置过滤器的顺序号
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        //调用 item-server需要判断权限
        //否则,不判断权限,直接跳过过滤代码

        //获取请求上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //从上下文对象获得调用的服务id
        String serviceId=
                (String)ctx.get(FilterConstants.SERVICE_ID_KEY);
        //如果服务id是item-server,返回true,否则返回false
        return"item-servicer".equalsIgnoreCase(serviceId);

    }

    @Override
    public Object run() throws ZuulException {
       //http://localhost:3001/item-service
        RequestContext ctx = RequestContext.getCurrentContext();

        HttpServletRequest request = ctx.getRequest();
        //从request去出token参数
        String token = request.getParameter("token");
        //如果没有token,null,"","   "
        if (StringUtils.isBlank((token))){
            //组织继续调用
            ctx.setSendZuulResponse(false);
            //直接向客户端返回响应
            //JsonResult - {code:400:未登录,data:null}
            String json = JsonResult.build().code(400).msg("未登录!").toString();
            ctx.addZuulRequestHeader("Content-Type","application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }
        return null;//在当前zuul版本中这个返回值不起任何作用
    }
}
